# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

from . import _

COVER_SOURCE = 'client/generic/covers'

THUMBNAIL_PROP = 'picture_front_thumbnail'
MAIN_PROP = 'picture_front'
EXTRA_PROP = 'picture_front_alternatives'

SIZE_PROPS = [MAIN_PROP, THUMBNAIL_PROP]

class ArtWriter:

    def __init__(self, client):
        self.client = client

    def write(self, size, ids, data, overwrite = False):
        def upd_ids(md5_hash):
            for id in ids:
                self.set_hash(id, size, md5_hash, overwrite)
        self.client.bindata.add(str(data), upd_ids)

    def set_hash(self, id, size, md5_hash, overwrite = False):
        def _write_hash(minfo):
            if size is None:
                return
            if SIZE_PROPS[size] == MAIN_PROP:
                if (MAIN_PROP in minfo) and (not overwrite):
                    the_prop = EXTRA_PROP
                    if EXTRA_PROP in minfo:
                        if (md5_hash not in 
                                (minfo[EXTRA_PROP]+';'+minfo[MAIN_PROP])):
                            new_prop = minfo[EXTRA_PROP]+';'+md5_hash
                        else:
                            return
                    else:
                        new_prop = md5_hash
                else:
                    the_prop = MAIN_PROP
                    new_prop = md5_hash
            elif SIZE_PROPS[size] == THUMBNAIL_PROP:
                if THUMBNAIL_PROP in minfo:
                    return
                else:
                    the_prop = THUMBNAIL_PROP
                    new_prop = md5_hash

            self.client.medialib.property_set(id, the_prop, new_prop,
                    COVER_SOURCE)

            #backup the old main property as an extra prop
            if ((the_prop == MAIN_PROP) and
                    (MAIN_PROP in minfo) and overwrite):
                self.set_hash(id, size, minfo[MAIN_PROP])
        
        self.client.medialib.get_info(id, cb=_write_hash)

